package com.auth.manage.auth.controller.user;

import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.RandomUtil;
import com.auth.manage.auth.constant.AuthConstant;
import com.auth.manage.auth.infra.exception.AuthErrorCode;
import com.auth.manage.auth.infra.exception.AuthException;
import com.auth.manage.auth.param.user.UserLoginByCaptchaParam;
import com.auth.manage.auth.param.user.UserRegisterParam;
import com.auth.manage.base.responce.BaseResponce;
import com.auth.manage.base.responce.MultipleResponce;
import com.auth.manage.base.responce.SingleResponce;
import com.auth.manage.common.notice.api.request.SendCaptchaRequest;
import com.auth.manage.common.notice.api.service.NoticeFacadeService;
import com.auth.manage.common.user.api.request.UserRegisterRequest;
import com.auth.manage.common.user.api.request.condition.UserQueryByTelephoneCondition;
import com.auth.manage.common.user.api.responce.UserResponce;
import com.auth.manage.common.user.api.service.UserFacadeService;
import com.auth.manage.web.vo.Result;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;



@RequiredArgsConstructor
@RestController
@RequestMapping("/auth/user")
public class UserAuthController {
    private final StringRedisTemplate redisTemplate;
    private final UserFacadeService userFacadeService;
    private final NoticeFacadeService noticeFacadeService;

    String captcha = "2314";
    @GetMapping("/getLoginCaptcha")
    public Result getLoginCaptcha(String telephone){
        // 1.生成验证码，存入Redis
        String captcha = RandomUtil.randomString(6);
        redisTemplate.opsForValue().set(AuthConstant.CAPTCHA_LOGIN_KEY_PREFIX + telephone, captcha);
        // 2.构建请求，发送给Notice服务
        SendCaptchaRequest request = new SendCaptchaRequest(telephone, captcha);
        BaseResponce responce = noticeFacadeService.sendCaptcha(request);
        if (responce.getSuccess()) {
            return Result.success();
        }else
            return Result.error(responce.getResponceCode(), responce.getResponceMessage());
    }

    @PostMapping("/loginByCaptcha")
    public Result login(@RequestBody @Validated UserLoginByCaptchaParam param){
        //  1.从Redis中获取验证码，和当前验证码比较
        String captcha = redisTemplate.opsForValue().get(AuthConstant.CAPTCHA_LOGIN_KEY_PREFIX + param.getTelephone());
        Assert.isTrue(StringUtils.equalsIgnoreCase(param.getCaptcha(), captcha), () -> new AuthException(AuthErrorCode.CAPTCHA_NOT_MATCH));
        // 2.远程调用user服务,判断手机号对应的用户是否存在
        Result result = new Result();
        MultipleResponce<UserResponce> responce = userFacadeService.queryByCondition(new UserQueryByTelephoneCondition(param.getTelephone()));
        responce.getData().stream().findFirst().ifPresentOrElse(userResponce -> {
            // 2.1 存在
            StpUtil.login(userResponce.getUserId(), new SaLoginModel().setIsLastingCookie(param.getRememberMe()));
            StpUtil.getSession().set("userInfo", userResponce);
            result.setSuccess(true);
            result.setData(userResponce);
        }, () -> {
            // 2.2 不存在，进行用户注册并登录
            UserRegisterRequest request = new UserRegisterRequest();
            request.setTelephone(param.getTelephone());
            SingleResponce<UserResponce> singleResponce = userFacadeService.register(request);
            if (singleResponce.getSuccess()){
                UserResponce userResponce = singleResponce.getData();
                StpUtil.login(userResponce.getUserId(), new SaLoginModel().setIsLastingCookie(param.getRememberMe()));
                StpUtil.getSession().set("userInfo", userResponce);
                result.setSuccess(true);
                result.setData(userResponce);
            }else {
                result.setCode(singleResponce.getResponceCode());
                responce.setResponceMessage(singleResponce.getResponceMessage());
            }
        });
        return result;
    }

    @PostMapping("/register")
    public Result register(UserRegisterParam param){
        // 1.校验验证码
        String captcha = redisTemplate.opsForValue().get(AuthConstant.CAPTCHA_REGISTER_KEY_PREFIX + param.getTelephone());
        Assert.isTrue(StringUtils.endsWithIgnoreCase(param.getCaptcha(), captcha), () -> new AuthException(AuthErrorCode.CAPTCHA_NOT_MATCH));
        // 2.构建请求
        UserRegisterRequest userRegisterRequest = new UserRegisterRequest(param.getTelephone(), param.getInviteCode());
        // 3.调用rpc接口
        SingleResponce<UserResponce> responce = userFacadeService.register(userRegisterRequest);
        if (responce.getSuccess() && responce.getData() != null){
            return Result.success(responce.getData());
        }
        return Result.error(responce.getResponceCode(), responce.getResponceMessage());
    }

    @PostMapping("/logout")
    public Result logout(){
        StpUtil.logout();
        return Result.success();
    }


}
